<template>
  <div class="userlist">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户列表</span>
        <el-button @click="$router.push('/layout/adduser')" style="float: right; padding: 3px 0"
          type="text">添加用户</el-button>
      </div>
      <!-- 搜索组件 -->
      <div class="condition_box">
        <el-input :disabled="loading" placeholder="请输入用户信息" v-model="keyword" class="input-with-select">
          <el-button :disabled="loading" @click="getusers" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </div>
      <!-- table表格 -->
      <el-table v-loading="loading" :data="users" height="380px" stripe border style="width: 100%">
        <el-table-column prop="id" label="编号" width="80"> </el-table-column>
        <el-table-column prop="username" label="昵称" width="150">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="150">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"> </el-table-column>
        <el-table-column label="注册时间" width="180">
          <!-- 如果在自定义的内容里，想要用当前对象的值，必须加template -->
          <template slot-scope="scope">
            <span>{{ scope.row.create_time | formate_date }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="65">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="角色" width="120">
          <template slot-scope="scope">
            <el-tag size="mini" type="danger">{{ scope.row.role_name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button @click="$router.push(`/layout/edituser/${scope.row.id}`)" size="mini" type="success">编辑</el-button>
            <el-button @click="deluser(scope.row)" size="mini" type="danger">删除</el-button>
            <el-button @click="user_role(scope.row)" size="mini" type="warning">分配角色</el-button>
            <el-button @click="updateStateFn(scope.row)" size="mini" type="into">{{ scope.row.mg_state ? '封号' : '解封'
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination :disabled="loading" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagenum" :page-sizes="[5, 10, 15, 20]" :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form :label-position="labelPosition" label-width="90px" :model="roleobj">
        <el-form-item label="当前用户">
          <el-input disabled v-model="roleobj.curr_user"></el-input>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-input disabled v-model="roleobj.curr_role"></el-input>
        </el-form-item>
        <el-form-item label="选择新角色">
          <el-select v-model="roleobj.new_role" placeholder="请选择">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="success" @click="saveRoleFn">分配角色</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUsersApi, deleteUserApi, putUserStateApi, putUserRoleApi } from "@/api/usersapi/index.js";
import { getRoles } from "@/api/role/index";
export default {
  data() {
    return {
      dialogVisible: false,
      labelPosition: "right",
      pagenum: 1,
      pagesize: 5,
      total: 0,
      loading: false,
      keyword: "",
      users: [],
      roles: [],
      roleobj: {
        id: 0,
        curr_user: "",
        curr_role: "",
        new_role: "",
      },
    }
  },
  filters: {
    formate_date(_val) {
      if (_val) {
        let date = new Date(_val);
        return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
      } else return "暂无注册时间信息";
    },
  },
  methods: {
    async saveRoleFn() {
      const res = await putUserRoleApi({ id: this.roleobj.id, rid: this.roleobj.new_role })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.roleobj.curr_user = '',
        this.roleobj.curr_role = '',
        this.roleobj.id = 0,
        this.roleobj.new_role = '',
        this.dialogVisible = false,
        this.getusers()
    },
    // 修改当前用户状态
    async updateStateFn(_row) {
      const res = await putUserStateApi(_row.id, !_row.mg_state)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg)
      this.getusers()
    },

    handleSizeChange(val) {
      this.pagesize = val
      this.getusers()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pagenum = val
      this.getusers()

    },
    deluser(_row) {
      this.$confirm(
        `确认删除编号[${_row.id}]昵称[${_row.username}]的用户吗`,
        "提示",
        {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          // 调用接口
          const res = await deleteUserApi(_row.id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg)
          this.getusers()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async user_role(_row) {
      this.roleobj.curr_user = _row.username;
      this.roleobj.curr_role = _row.role_name;
      this.roleobj.id = _row.id
      // 获取所哟可用的角色数据
      const res = await getRoles();
      this.roles = res.data
      this.dialogVisible = true;
    },
    //分配角色对话框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    //加载用户列表数据
    async getusers() {
      this.loading = true
      const res = await getUsersApi({
        pagenum: this.pagenum,
        pagesize: this.pagesize,
        query: this.keywords
      });
      this.users = res.data.users
      this.total = res.data.total
      this.loading = false
    }
  },
  created() {
    this.getusers()
  }
};
</script>

<style lang="scss" scoped>
.userlist {
  .el-pagination {
    margin-top: 15px;
  }

  .condition_box {
    width: 330px;
    margin-bottom: 15px;
  }
}
</style>